<?php
namespace app\controller;
use think\Validate;
use \app\model\User as ModelUser;
use \app\validate\User as ValidateUser;
use think\facade\Session;

class User
{
    //查看用户信息，根据cookie或者参数的account来
    public function index()
    {
        if(!Session::has('user')){
            return ajaxRespone([],"用户未登录","-1");
        }
        else{
            $user = ModelUser::where(['account'=>Session::get('user')])->withoutField('pwd')->select();

            return ajaxObjRespone($user);
        }

    }
    public function signIn()
    {
        try {
            validate(ValidateUser::class)
                ->scene('siginIn')
                ->check($_POST);
        } catch (ValidateException $e) {
            return ajaxRespone([],$e->getError(),"-1");
        }
        //是否已经存在
        $pwd=md5($_POST['pwd']);
        $user = ModelUser::where(['account'=>$_POST['account'],'pwd'=>$pwd])->findOrEmpty();
        if ($user->isEmpty()) {
            return ajaxRespone([],"登录失败,该用户不存在,或密码错误","-1");
        }
        else{
            Session::set('user',$user->account);
            Session::set('userid',$user->id);

            return ajaxRespone([],"登录成功");
        }
        return ajaxRespone();
    }
    public  function signOut(){
        if(Session::has('user')){
            Session::clear();
            return ajaxRespone([],"退出成功");
        }else{
            return ajaxRespone([],"退出失败，当前没有登录任何账号","-1");
        }

    }
    public function register(){

        try {
            validate(ValidateUser::class)
                ->scene('register')
                ->check($_POST);
        } catch (ValidateException $e) {
            return ajaxRespone([],$e->getError(),"-1");
        }
        //是否已经存在
        $user = ModelUser::where('account', $_POST['account'])->findOrEmpty();
        if (!$user->isEmpty()) {
            return ajaxRespone([],"注册失败,该用户已存在","-1");
        }
        //开始注册
        $user = new ModelUser;
        $user->save([
            'account'  =>  $_POST['account'],
            'pwd' =>  md5($_POST['pwd'])
        ]);
        if($user->id){
            return ajaxRespone([],"注册成功");
        }
        else{
            return ajaxRespone([],"注册失败","-1");
        }

    }
    public  function update(){

    }
}